<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Express extends Stourweb_Controller
{
    public function before()
    {
        parent::before();

        $this->assign('parentkey', $this->params['parentkey']);
        $this->assign('itemid', $this->params['itemid']);
    }

    public function action_plan()
    {
        $this->display('stourtravel/express/plan');
    }

    public function action_pickup()
    {
        $action = Arr::get($_GET,'action');
        if(empty($action))
        {
            $list  = Model_Express_Pickup::get_list();
            $this->assign('list',$list);
            $this->display('stourtravel/express/pickup');
        }
        elseif($action=='add')
        {
            $inser_arr = array(
                'title'=>'自提点名称',
                'mobile'=>'自提点电话',
                'address'=>'自提点地址',
                'isopen'=>1
            );
            list($key,$rownum) = DB::insert('express_pickup',array_keys($inser_arr))->values(array_values($inser_arr))->execute();
            if($key)
            {
                $inser_arr['id'] = $key;
                echo json_encode(array('status'=>true,'msg'=>'添加成功','data'=>$inser_arr));
            }
            else
            {
                echo json_encode(array('status'=>false,'msg'=>'添加失败'));
            }
        }
        elseif($action=='save')
        {

            $title = Arr::get($_POST,'title');
            $isopen = Arr::get($_POST,'isopen');
            $mobile = Arr::get($_POST,'mobile');
            $address = Arr::get($_POST,'address');
            foreach($title as $key=>$val)
            {
                $update_arr = array(
                    'title'=>$val,
                    'mobile'=>$mobile[$key],
                    'address'=>$address[$key],
                    'isopen'=>$isopen[$key],
                );
                DB::update('express_pickup')->set($update_arr)->where('id','=',$key)->execute();
            }

            echo 'ok';
        }
        elseif($action=='del')
        {
            $id = $_POST['id'];
            DB::delete('express_pickup')->where('id','=',$id)->execute();
            echo json_encode(array('status'=>true));
        }


    }

    public function action_plan_edit()
    {
        $id = $_GET['templateid'];
        if($id)
        {
            $info = DB::select()->from('express_template')
                ->where('id','=',$id)
                ->execute()->current();
            $info['planlist'] = Model_Express_Plan::get_template_planlist($id);
            foreach ($info['planlist'] as $k1=>$v1){
                $cityList=$v1["citylist"];
                if($cityList){
                    $list = DB::query(1,"select parent.cityname as pname,child.cityname as cname from sline_express_destination as parent join sline_express_destination as child on parent.id=child.pid where child.id in ($cityList)")->execute()->as_array();
                    $tree=array();
                    foreach ($list as &$val) {
                        $tree[$val['pname']]['pname'] = $val['pname'];
                        $tree[$val['pname']]['children'].=$val['cname'].'、';
                    }
                    $array =  array_values($tree);
                    $new='';
                    mb_internal_encoding("UTF-8");
                    $encoding = mb_internal_encoding();
                    foreach ($array as $k2=>$v2) {
                        $city_list=St_Functions::mb_rtrim($v2['children'], "、",$encoding);
                        $new.='<div style="color: red">'.$v2['pname'].'</div>'.'<div>'.$city_list.'</div>';
                    }
                    $info['planlist'][$k1]['city_titlelist']=$new;
                }else{
                    $info['planlist'][$k1]['city_titlelist']=array();
                }
            }
        }
        $this->assign('info',$info);
        $this->assign('id',$id);
        $this->display('stourtravel/express/plan_edit');
    }

    /**
     * @function 设置配送区域
     */
    public function action_dialog_address()
    {
        $provincelist =  $_GET['provincelist'];
        $citylist =  $_GET['citylist'];
        $planid =  $_GET['planid'];
        $tops = Model_Express_Destination::get_address_city_list(0);
        $province_arr = explode(',',$provincelist);
        $city_arr = explode(',',$citylist);
        foreach ($tops as &$t)
        {
            $t['childnum'] = DB::select(DB::expr('count(*) as num'))
                ->from('express_destination')
                ->where(" pid={$t['id']}")
                ->execute()->get('num');
            if(in_array($t['id'],$province_arr))
            {
                $num = DB::select(DB::expr('count(*) as num'))
                    ->from('express_destination')
                    ->where("id in ($citylist) and pid={$t['id']}")
                    ->execute()->get('num');
                $t['num'] = $num;
            }

            //名称截取
            if(strlen($t['cityname'])>12)
            {
                $t['shortname'] = mb_substr($t['cityname'],0,4).'...';
            }
            else
            {
                $t['shortname']  = $t['cityname'];
            }


        }
        unset($t);
        $this->assign('province_arr',$province_arr);
        $this->assign('city_arr',$city_arr);

        $this->assign('citylist',$citylist);
        $this->assign('planid',$planid);
        $this->assign('tops',$tops);
        $this->display('stourtravel/express/dialog_address');
    }


    /**
     * @function 加载更多模板信息
     */
    public function action_ajax_more()
    {
        $page = $_POST['page'];
        $keyword = $_POST['keyword'];
        $pagesize = 10;
        $offset = ($page-1) *  $pagesize;
        $where =1;
        if($keyword){
            $where.= " and title like '%$keyword%'";
        }
        $list = DB::select()
            ->from('express_template')
            ->where($where)
            ->order_by('id','asc')
            ->offset($offset)
            ->limit($pagesize)
            ->execute()
            ->as_array();
        foreach ($list as &$l)
        {
            $l['planlist'] = Model_Express_Plan::get_template_planlist($l['id']);
            $l['modtime'] = date('Y-m-d H:i:s',$l['modtime']);

            foreach ($l['planlist'] as $k1=>$v1){
                $cityList=$v1["citylist"];
                if($cityList){
                    $list2 = DB::query(1,"select parent.cityname as pname,child.cityname as cname from sline_express_destination as parent join sline_express_destination as child on parent.id=child.pid where child.id in ($cityList)")->execute()->as_array();
                    $tree=array();
                    foreach ($list2 as &$val) {
                        $tree[$val['pname']]['pname'] = $val['pname'];
                        $tree[$val['pname']]['children'].=$val['cname'].'、';
                    }
                    $array =  array_values($tree);
                    $new='';
                    mb_internal_encoding("UTF-8");
                    $encoding = mb_internal_encoding();
                    foreach ($array as $k2=>$v2) {
                        $city_list=St_Functions::mb_rtrim($v2['children'], "、",$encoding);
                        $new.='<div style="color: red">'.$v2['pname'].'</div>'.'<div>'.$city_list.'</div>';
                    }
                    $l['planlist'][$k1]['city_titlelist']=$new;
                }else{
                    $l['planlist'][$k1]['city_titlelist']=array();
                }
            }
        }
        unset($l);
        if(count($list)<$pagesize)
        {
            $outpage = -1;
        }
        else
        {
            $outpage = ++$page;
        }
        echo  json_encode(array('list'=>$list,'page'=>$outpage));

    }

    /**
     * @function 获取下级城市
     */
    public function action_ajax_get_nextcity()
    {
        $pid = $_POST['pid'];
        $list = Model_Express_Destination::get_address_city_list($pid);

        foreach ($list as &$l)
        {
            //名称截取
            if(strlen($l['cityname'])>24)
            {
                $l['shortname'] = mb_substr($l['cityname'],0,8).'...';
            }
            else
            {
                $l['shortname']  = $l['cityname'];
            }
        }
        echo  json_encode(array('list'=>$list));
    }

    /**
     * @function 根据ids 获取显示名称
     */
    public function action_ajax_get_address_title()
    {
        $citylist = $_POST['citylist'];
//        $cityname = Model_Express_Destination::get_address_title($citylist);
//        echo json_encode(array('cityname'=>$cityname));
        $list =DB::query(1,"select parent.cityname as pname,child.cityname as cname from sline_express_destination as parent join sline_express_destination as child on parent.id=child.pid where child.id in ($citylist)")->execute()->as_array();
        foreach ($list as &$val) {
            $tree[$val['pname']]['pname'] = $val['pname'];
            $tree[$val['pname']]['children'].=$val['cname'].'、';
        }
        $array =  array_values($tree);
        $new='';
        mb_internal_encoding("UTF-8");
        $encoding = mb_internal_encoding();
        foreach ($array as $k2=>$v2) {
            $city_list=St_Functions::mb_rtrim($v2['children'], "、",$encoding);
            $new.='<div style="color: red">'.$v2['pname'].'</div>'.'<div>'.$city_list.'</div>';
        }
        echo json_encode(array('cityname'=>$new));
    }

    //保存运费模板
    public function action_ajax_save_template()
    {
        $title = $_POST['title'];
        $type = $_POST['type'];
        $templateid = $_POST['templateid'];
        $provincelist = $_POST['provincelist'];
        $citylist = $_POST['citylist'];
        $start_num = $_POST['start_num'];
        $start_price = $_POST['start_price'];
        $continue_num = $_POST['continue_num'];
        $continue_price = $_POST['continue_price'];
        $data = array(
            'title'=>$title,
            'type'=>$type,
            'modtime'=>time(),
        );
        $new_plan = array();
        $old_plan = array();
        //区别新增的区域和以前的区域
        foreach ($provincelist as $key=>$val)
        {
            $plan = array(
                'provincelist'=>$val,
                'citylist'=>$citylist[$key],
                'start_num'=>$start_num[$key],
                'start_price'=>$start_price[$key],
                'continue_num'=>$continue_num[$key],
                'continue_price'=>$continue_price[$key],
            );
            if(strpos($key,'new')!==false)
            {
                $new_plan[] = $plan;
            }
            else
            {
                $old_plan[$key] = $plan;
            }
        }
        //保存基础
        if($templateid)
        {
            DB::update('express_template')->set($data)->where('id','=',$templateid)->execute();
        }
        else
        {
            $data['addtime'] = time();
            list($templateid) = DB::insert('express_template',array_keys($data))->values(array_values($data))->execute();
        }
        //保存区域
        foreach ($old_plan as $key=>$plan)
        {
            DB::update('express_plan')->set($plan)->where('id','=',$key)->execute();
        }
        foreach ($new_plan as $plan)
        {
            $plan['templateid'] = $templateid;
            DB::insert('express_plan',array_keys($plan))->values(array_values($plan))->execute();
        }
        echo json_encode(array('templateid'=>$templateid));

    }

    /**
     * @function 删除配送区域
     */
    public function action_ajax_del_plan()
    {
        $id = $_POST['planid'];
        if(strpos($id,'new'))
        {
            exit(json_encode(array('status'=>1)));

        }
        DB::delete('express_plan')->where('id','=',$id)->execute();

        exit(json_encode(array('status'=>1)));

    }

    /**
     * @function 修改运费模板
     */
    public function action_ajax_update_template()
    {
        $action = $_POST['action'];
        $id = $_POST['id'];
        if($action=='del')
        {
            DB::delete('express_template')->where('id','=',$id)->execute();
            DB::delete('express_plan')->where('templateid','=',$id)->execute();
        }
        elseif($action=='clone')
        {
            $template = DB::select()->from('express_template')
                ->where('id','=',$id)->execute()->current();
            $template['addtime'] = $template['modtime'] = time();
            unset($template['id']);
            $planlist = DB::select()->from('express_plan')->where('templateid','=',$id)->execute()->as_array();
            list($newid) = DB::insert('express_template',array_keys($template))->values(array_values($template))->execute();
            if($newid)
            {
                foreach ($planlist as $plan)
                {
                    unset($plan['id']);
                    $plan['templateid'] = $newid;
                    DB::insert('express_plan',array_keys($plan))->values(array_values($plan))->execute();

                }
            }

        }
        echo json_encode(array('status'=>1));
    }


    // 快递配置
    public function action_config()
    {
        $fields = array('cfg_malls_express_open', 'cfg_malls_express_key', 'cfg_malls_express_company', 'cfg_malls_express_customer');
        $config = Model_Sysconfig::get_configs(0, $fields);
        $cfg_malls_express_company = $config['cfg_malls_express_company'];
        if($cfg_malls_express_company)
        {
            $company_list = DB::query(1,"SELECT * FROM sline_malls_express_company_k100 WHERE id IN({$cfg_malls_express_company})")->execute()->as_array();
            $this->assign('company_list',$company_list);
        }

        $this->assign('config', $config);
        $this->display('stourtravel/express/config');
    }


    // 快递公司
    public function action_dialog_express()
    {
        $ids = Arr::get($_GET,'ids');
        $idArr = explode(',',$ids);
        // 获取全部公司列表
        $company_list = DB::query(1,"SELECT * FROM sline_malls_express_company_k100")->execute()->as_array();
        $new_arr = array();
        foreach($company_list as $v)
        {
            $szm = Common::getPinYin($v['company_name'],1);
            $head = strtoupper(substr($szm,0,1));
            if(!isset($new_arr[$head]))
            {
                $new_arr[$head] = array();
            }
            $new_arr[$head][] = $v;
        }
        ksort($new_arr);
        $this->assign('company_list',$new_arr);
        $this->assign('idArr',$idArr);
        $this->display('stourtravel/express/dialog_company');
    }


    // 保存快递配置
    public function action_save_express_config()
    {
        $is_open = Arr::get($_POST,'is_open');
        $express_key = Arr::get($_POST,'express_key');
        $ids = Arr::get($_POST,'ids');
        $express_customer = Arr::get($_POST,'express_customer');

        $data = array(
            'cfg_malls_express_open'=> $is_open,
            'cfg_malls_express_key'=> $express_key,
            'cfg_malls_express_company'=> $ids,
            'cfg_malls_express_customer'=> $express_customer,
        );

        foreach ($data as $config_key => $config_value)
        {
            $res = DB::select()->from("sysconfig")->where('varname', '=', $config_key)->execute()->current();
            if($res)
            {
                DB::update("sysconfig")->set(array('value' => $config_value,'webid'=> 0))->where('varname', '=', $config_key)->execute();
            }
            else
            {
                $n_data = array(
                    'varname' => $config_key,
                    'value' => $config_value,
                    'webid' => 0,
                );
                DB::insert("sysconfig",array_keys($n_data))->values(array_values($n_data))->execute();
            }
        }

        exit(json_encode(array('status'=> true,'msg'=> '保存成功')));
    }

}